package org.shinetour.sms.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import org.shinetour.sms.common.utils.StringUtils;
import org.shinetour.sms.model.*;
import org.shinetour.sms.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * @ProjectName: shinetour
 * @Package: org.shinetour.sms.service.impl
 * @Description:
 * @Author: ZhenHua Wang
 * @CreateDate: 2020/4/21 17:49
 */
@Service
public class SendSmsServiceImpl implements ISendSmsService {

    @Autowired
    ISmsRecordService smsRecordService;
    @Autowired
    ISmsTemplateService templateService;
    @Autowired
    ITemplateParamsService templateParamsService;
    @Autowired
    IRLSmsService supplierService;
    @Autowired
    ISmsErrorRecordService errorRecordService;

    /**
     * @Description: 发送短信
     * @Author: ZhenHua Wang
     * @CreateDate: 2020/4/1 14:35
     */
    @Override
    public ResultModel sendSms(Map<String, String> map) {
        ResultModel res = new ResultModel();
        SmsTemplate template;
        String templateCode = map.getOrDefault("templateCode", "");
        if (!StrUtil.isEmpty(templateCode)) {
            template = templateService.getOne(new QueryWrapper<SmsTemplate>().eq("template_code", templateCode));
        } else {
            String templateAlias = map.getOrDefault("template", "");
            if (templateAlias.isEmpty()) {
                return res.error("模板参数[template]为空,请检查后重试！");
            }
            template = templateService.getOne(new QueryWrapper<SmsTemplate>().eq("template_alias", templateAlias));
        }
        if (null == template) {
            return res.error("根据模板参数[template]，没能查询到对应的短信模板,请检查后重试！");
        }
        List<TemplateParams> templateParamsList = templateParamsService.list(
                new QueryWrapper<TemplateParams>().eq("template_code", template.getTemplateCode()));
        if (null == templateParamsList || templateParamsList.isEmpty()) {
            return res.error("根据模板参数[template]，没能查询到对应的模板参数,请检查后重试！");
        }
        //按照参数顺序排序
        templateParamsList.sort(Comparator.comparing(TemplateParams::getParamIndex));
        //有序Json,同时组装短信内容
        JSONObject jsonParams = new JSONObject(new LinkedHashMap());
        String content = template.getTemplateContent();
        for (int i = 0; i < templateParamsList.size(); i++) {
            String paramKey = templateParamsList.get(i).getParamKey();
            String paramValue = map.getOrDefault(paramKey, "");
            if (paramValue.isEmpty()) {
                return res.error(String.format("参数[%s]缺失或为空,请检查后重试！", paramKey));
            }
            content = content.replace("{" + (i + 1) + "}", paramValue);
            jsonParams.put(paramKey, paramValue);
        }
        String mobile = map.getOrDefault("mobile", "");
        if (!StringUtils.isMobile(mobile)) {
            return res.error(String.format("参数[%s]不是可用手机号,请检查后重试！", mobile));
        }
        SmsRecord record = new SmsRecord();
        record.setMobile(mobile);
        record.setTemplateCode(template.getTemplateCode());
        record.setSmsContent(content);
        record.setParams(jsonParams.toString());
        record.setCreateTime(new Date());
        record.setFromSystem(map.getOrDefault("system", ""));
        record.setCreator(map.getOrDefault("creator", ""));
        //保存短信发送记录
        smsRecordService.save(record);
        //调用供应商接口，发送短信
        ResultModel<HashMap<String, Object>> supplierRes = supplierService.sendSms(record);
        //保存短信发送结果
        UpdateWrapper<SmsRecord> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("iid", record.getIid());
        SmsRecord updateModel = new SmsRecord();
        if (supplierRes.isSuccess()) {
            updateModel.setSendSuccess(true);
            updateModel.setSuccessTime(new Date());
            smsRecordService.update(updateModel, updateWrapper);
            res = res.success("短信发送成功！");
        } else {
            updateModel.setSendSuccess(false);
            updateModel.setFailureTimes(1);
            smsRecordService.update(updateModel, updateWrapper);
            SmsErrorRecord errorRecord = new SmsErrorRecord();
            errorRecord.setSendTime(new Date());
            String errorInfo = "错误码:" + supplierRes.getData().get("statusCode") + " ;错误信息:" + supplierRes.getData().get("statusMsg");
            errorRecord.setErrorInfo(errorInfo);
            res = res.error(supplierRes.getData().get("statusMsg"));
        }
        return res;
    }
}
